package com.wu.ssm.spring.ioc;

import com.wu.ssm.spring.utils.ReflectionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by wzf on 2018/11/26/026.
 */
public class BeanHelper {


    /**
     * 用于存放bean和实例的映射关系
     */
    private  static final Map<Class<?>,Object> BEAN_MAP = new HashMap<>();

    static {
        Set<Class<?>> allBeanlassSet =  ClassHelper.getAllBeanClassSet();
        for (Class<?> clazz:allBeanlassSet
             ) {
            Object obj = ReflectionUtil.newInstance(clazz);
            BEAN_MAP.put(clazz, obj);
        }
    }

    /**
     * 获取bean Map
     */
    public static Map<Class<?>,Object> getBeanMap(){
       return BEAN_MAP;
    }

    /**
     * 获取bean实例
     */
    public static <T> T getBean(Class<T> clazz){
        if(!BEAN_MAP.containsKey(clazz)){
            throw new RuntimeException("没有实例" + clazz);
        }
        return (T) BEAN_MAP.get(clazz);
    }

    /**
     * 设置bean实例
     */
    public static void setBean(Class<?> clazz, Object obj){
        BEAN_MAP.put(clazz, obj);
    }

}
